package com.zw.mes.module.assemble.service;

import com.zw.mes.entity.sys.Dept;
import com.zw.mes.entity.sys.User;
import com.zw.mes.module.assemble.entity.AsseAssemblyDetail;
import com.zw.mes.module.assemble.entity.AsseAssemblySheet;
import com.zw.mes.module.assemble.mapper.AssMakeMapper;
import com.zw.mes.module.assemble.mapper.DispatchMapper;
import com.zw.mes.module.assemble.model.CraMakeModel;
import com.zw.mes.module.assemble.model.ProStructModel;
import com.zw.mes.module.assemble.model.ProdOrdModel;
import com.zw.mes.module.assemble.repository.AsseAssemblyDetailRepository;
import com.zw.mes.module.assemble.repository.AsseAssemblySheetRepository;
import com.zw.mes.module.system.mapper.DeptMapper;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.util.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:
 * @Author: China.wsg
 * @Date: 2021/04/23 14:12
 */
@Service
@SuppressWarnings("all")
public class DispatchService {

    @Autowired
    private DispatchMapper dispatchMapper;
    @Autowired
    private LogService logService;
    @Autowired
    private AsseAssemblySheetRepository assemblySheetRepository;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private AsseAssemblyDetailRepository assemblyDetailRepository;
    @Autowired
    private AssMakeMapper makeMapper;

    /**
     * 获取生产令列表数据
     */
    public List<ProdOrdModel> prodOrdListByCode(String code) {
        return dispatchMapper.prodOrdListByCode(code);
    }

    /**
     * 根据项目号、专业查询部分
     */
    public List<ProStructModel> findPartByProCodeAndSpecial(String code, String special) {
        return dispatchMapper.findPartByProCodeAndSpecial(code, special);
    }

    /**
     * 查询图号列表
     */
    public List<CraMakeModel> findCarMakeListByCodeAndPartId(String code, String special, Integer partId, String drawNo) {
        return dispatchMapper.findCarMakeListByCodeAndPartId(code, special, partId, drawNo);
    }

    /**
     * 查图号
     */
    public CraMakeModel findDrawNoById(Integer id) {
        return dispatchMapper.findDrawNoById(id);
    }

    /**
     * 保存装配派工单
     */
    @Transactional(rollbackFor = Exception.class)
    public int save(AsseAssemblySheet assemblySheet, String[] route, Integer[] orderNo, String[] process, String[] comment) {
        // 判断该图号是否已经创建装配派工单，不允许二次创建（暂无该需求，需要时再添加）
        /*if (c != null) {
            return 0;
        }*/
        User u = ShiroUtils.getUser();
        if(assemblySheet.getPartId() != null && assemblySheet.getPartId() != 0)
        {
            ProStructModel proStructModel = dispatchMapper.findPartById(assemblySheet.getPartId());
            if(proStructModel != null)
            {
                assemblySheet.setPart(dispatchMapper.findPartById(assemblySheet.getPartId()).getProPart());
            }
        }
        List<Dept> depts = deptMapper.findDeptByIds(assemblySheet.getDeptId());
        if (depts != null && depts.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < depts.size(); i++) {
                sb.append(depts.get(i).getName()).append(",");
            }
            assemblySheet.setDeptName(StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), ","));
        }
        assemblySheet.setCreateCode(u.getAccount());
        assemblySheet.setCreateName(u.getName());
        // 类型为自动化时，才存入‘注意事项’字段
        if (assemblySheet.getSpecial().equals("自动化")) {
            assemblySheet.setRemark(assemblySheet.getRemark()
                    .replaceAll("\r\n|\r|\n|\n\r", "<br>")
                    .replaceAll(" ", "&ensp;"));
        } else {
            assemblySheet.setRemark("");
        }
        assemblySheetRepository.save(assemblySheet);

        // 类型为非自动化（机械、流体）时，才存入装配路线
        if (!assemblySheet.getSpecial().equals("自动化")) {
            // 设置装配单从表
            for (int i = 0; i < route.length; i++) {
                AsseAssemblyDetail detail = new AsseAssemblyDetail();
                detail.setSheetId(assemblySheet.getId());
                detail.setRoute(route[i]);
                detail.setOrderNo(orderNo[i]);
                detail.setProcess(process[i]);
                if (comment.length > 0) {
                    detail.setComment(comment[i]
                            .replaceAll("\r\n|\r|\n|\n\r", "<br>")
                            .replaceAll(" ", "&ensp;"));
                }
                detail = assemblyDetailRepository.save(detail);
            }
        }
        logService.saveLog("创建装配派工单", "派工单ID：" + assemblySheet.getId() + "，生产令号：" + assemblySheet.getProdNo()
                + "<br>项目名称：" + assemblySheet.getProName() + "<br>类型：" + assemblySheet.getSpecial() + "<br>部分：" + assemblySheet.getPart()
                + "<br>装配图号：" + assemblySheet.getDrawNo() + "<br>装配图名：" + assemblySheet.getDrawName());
        return 1;
    }

    /**
     * 提交列表数据
     */
    public List<AsseAssemblySheet> findAssemblySheetById(AsseAssemblySheet assemblySheet) {
        return dispatchMapper.findAssemblySheetById(assemblySheet);
    }

    /**
     * 装配单从表（工序表）
     */
    public List<AsseAssemblyDetail> findAssemblyDetailBySheetId(Integer sheetId) {
        return dispatchMapper.findAssemblyDetailBySheetId(sheetId);
    }

    /**
     * 删除装配派工单
     */
    @Transactional(rollbackFor = Exception.class)
    public int delAsseSheetById(Integer id) {
        AsseAssemblySheet assemblySheet = assemblySheetRepository.getOne(id);
        // 校验：删除之前判断是否存在已提交的装配零件
        Integer cn = makeMapper.getMakeCommitCountBySheetId(id);
        Integer cd = dispatchMapper.getTransFlgBySheetId(id);
        if (cn.compareTo(0) > 0 && cd.compareTo(0) != 0) {
            return 0;
        }

        logService.saveLog("删除装配派工单", "派工单ID：" + assemblySheet.getId() + "，生产令号：" + assemblySheet.getProdNo()
                + "<br>项目名称：" + assemblySheet.getProName() + "<br>类型：" + assemblySheet.getSpecial() + "<br>部分：" + assemblySheet.getPart()
                + "<br>装配图号：" + assemblySheet.getDrawNo() + "<br>装配图名：" + assemblySheet.getDrawName());

        assemblySheet.setIsDel(1);// 删除状态 0：默认， 1：删除
        assemblySheetRepository.save(assemblySheet);

        // 删除制作件明细表
        makeMapper.deleteAssemblyMakeBySheetId(id);
        // 删除采购明细表
        makeMapper.deleteAssemblyBuyBySheetId(id);
        return 1;
    }

    /**
     * 撤销装配派工单
     */
    @Transactional(rollbackFor = Exception.class)
    public AsseAssemblySheet cancelAsseSheetById(Integer id) {
        AsseAssemblySheet assemblySheet = assemblySheetRepository.getOne(id);
        logService.saveLog("撤销装配派工单", "派工单ID：" + assemblySheet.getId() + "，生产令号：" + assemblySheet.getProdNo()
                + "<br>项目名称：" + assemblySheet.getProName() + "<br>类型：" + assemblySheet.getSpecial() + "<br>部分：" + assemblySheet.getPart()
                + "<br>装配图号：" + assemblySheet.getDrawNo() + "<br>装配图名：" + assemblySheet.getDrawName());

        assemblySheet.setStatus(1);// 1=保存 2=提交 3=审核通过
        assemblySheetRepository.save(assemblySheet);
        return assemblySheet;
    }

    /**
     * 提交装配派工单
     */
    @Transactional(rollbackFor = Exception.class)
    public AsseAssemblySheet subAsseSheetById(Integer id) {
        AsseAssemblySheet assemblySheet = assemblySheetRepository.getOne(id);
        logService.saveLog("提交装配派工单", "派工单ID：" + assemblySheet.getId() + "，生产令号：" + assemblySheet.getProdNo()
                + "<br>项目名称：" + assemblySheet.getProName() + "<br>类型：" + assemblySheet.getSpecial() + "<br>部分：" + assemblySheet.getPart()
                + "<br>装配图号：" + assemblySheet.getDrawNo() + "<br>装配图名：" + assemblySheet.getDrawName());

        assemblySheet.setStatus(2);// 1=保存 2=提交 3=审核通过
        assemblySheetRepository.save(assemblySheet);

        /** 非自动化时，将工序插入装配路线表 */
        if (!assemblySheet.getSpecial().equals("自动化")) {
            // 如果存在转序的路线不变，没转序的路线删除并重新插入
            dispatchMapper.deleteNotTransAssemblyRouteBySheetId(id);
            dispatchMapper.insertAssemblyRoute(id);
            dispatchMapper.updateNotTransOneRouteRecNum(id, assemblySheet.getDrawNum());
        }

        /** 更新排产计划反馈信息表排产提交时间信息 */
        String prprCod = "";
        if (assemblySheet.getSpecial().equals("机械")) {
            prprCod = "r15";
        } else if (assemblySheet.getSpecial().equals("流体")) {
            prprCod = "r16";
        } else if (assemblySheet.getSpecial().equals("自动化")) {
            prprCod = "r17";
        }
        dispatchMapper.updateProdPlaRetDate(assemblySheet.getProdNo(), prprCod);

        return assemblySheet;
    }

    /**
     * 修改装配派工单
     */
    @Transactional(rollbackFor = Exception.class)
    public int edit(AsseAssemblySheet assemblySheet, String[] route, Integer[] orderNo, String[] process, String[] comment) {
        /** 更新该装配单主表 */
        // 取得原装配派工单主单，如果存储转序 主单只允许修改要求完成时间、重量Kg、部门字段
        Integer transFlg = dispatchMapper.getTransFlgBySheetId(assemblySheet.getId());
        AsseAssemblySheet oldSheet = assemblySheetRepository.getOne(assemblySheet.getId());
        if (transFlg.compareTo(0) == 0) {
            if (assemblySheet.getPartId() != null && assemblySheet.getPartId() !=0)
            {
                // 未转序
                assemblySheet.setPart(dispatchMapper.findPartById(assemblySheet.getPartId()).getProPart());
            }

            List<Dept> depts = deptMapper.findDeptByIds(assemblySheet.getDeptId());
            if (depts != null && depts.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < depts.size(); i++) {
                    sb.append(depts.get(i).getName()).append(",");
                }
                assemblySheet.setDeptName(StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), ","));
            }
            assemblySheet.setCreateCode(oldSheet.getCreateCode());
            assemblySheet.setCreateName(oldSheet.getCreateName());
            // 类型为自动化时，才存入‘注意事项’字段
            if (assemblySheet.getSpecial().equals("自动化")) {
                assemblySheet.setRemark(assemblySheet.getRemark()
                        .replaceAll("\r\n|\r|\n|\n\r", "<br>")
                        .replaceAll(" ", "&ensp;"));
            } else {
                assemblySheet.setRemark("");
            }
            assemblySheetRepository.save(assemblySheet);
        } else {
            // 存在转序
            oldSheet.setDrawWeight(assemblySheet.getDrawWeight());
            oldSheet.setCompTime(assemblySheet.getCompTime());
            oldSheet.setDeptId(assemblySheet.getDeptId());
            List<Dept> depts = deptMapper.findDeptByIds(assemblySheet.getDeptId());
            if (depts != null && depts.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < depts.size(); i++) {
                    sb.append(depts.get(i).getName()).append(",");
                }
                oldSheet.setDeptName(StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), ","));
            }
            assemblySheetRepository.save(oldSheet);

            // 由于前台控件disable属性设定原因，Special值传不进来，所以 在此处进行赋值，用于明细插入判断
            assemblySheet.setSpecial(oldSheet.getSpecial());
        }

        /** 更新该装配单从表 */
        // 删除装配派工单从表
        dispatchMapper.deleteAssemblyDetailBySheetId(assemblySheet.getId());
        // 类型为非自动化（机械、流体）时，才存入装配路线
        if (!assemblySheet.getSpecial().equals("自动化")) {
            // 更新装配单从表
            for (int i = 0; i < route.length; i++) {
                AsseAssemblyDetail detail = new AsseAssemblyDetail();
                detail.setSheetId(assemblySheet.getId());
                detail.setRoute(route[i]);
                detail.setOrderNo(orderNo[i]);
                detail.setProcess(process[i]);
                if (comment.length > 0) {
                    detail.setComment(comment[i]
                            .replaceAll("\r\n|\r|\n|\n\r", "<br>")
                            .replaceAll(" ", "&ensp;"));
                }
                detail = assemblyDetailRepository.save(detail);
            }
        }
        logService.saveLog("修改装配派工单", "派工单ID：" + assemblySheet.getId() + "，生产令号：" + assemblySheet.getProdNo()
                + "<br>项目名称：" + assemblySheet.getProName() + "<br>类型：" + assemblySheet.getSpecial() + "<br>部分：" + assemblySheet.getPart()
                + "<br>装配图号：" + assemblySheet.getDrawNo() + "<br>装配图名：" + assemblySheet.getDrawName());
        return 1;
    }

    /**
     * @Author wsg
     * @Date 10:29 2021/6/9
     * @Description 自动化装配任务反馈 列表
     **/
    public List<AsseAssemblySheet> findAssemblySheeteElectric(AsseAssemblySheet assemblySheet) {
        return dispatchMapper.findAssemblySheeteElectric(assemblySheet);
    }

    /**
     * @Author wsg
     * @Date 14:10 2021/6/9
     * @Description 自动化装配进度反馈
     **/
    @Transactional(rollbackFor = Exception.class)
    public int saveEleBake(AsseAssemblySheet assemblySheet) {
        AsseAssemblySheet oldAsseSheet = assemblySheetRepository.getOne(assemblySheet.getId());
        // 更新自动化装配进度反馈
        dispatchMapper.updateEleBake(assemblySheet);

        String[] statusMes = {"", "未开始", "执行中", "已完成"};
        logService.saveLog("自动化装配进度反馈", "派工单ID：" + oldAsseSheet.getId() + "，生产令号：" + oldAsseSheet.getProdNo()
                + "<br>项目名称：" + oldAsseSheet.getProName() + "<br>类型：" + oldAsseSheet.getSpecial() + "；部分：" + oldAsseSheet.getPart()
                + "<br>装配图号：" + oldAsseSheet.getDrawNo() + "；装配图名：" + oldAsseSheet.getDrawName()
                + "<br>装配状态：" + statusMes[oldAsseSheet.getEleStatus()] + "=>" + statusMes[assemblySheet.getEleStatus()]
                + "<br>开始时间：" + oldAsseSheet.getEleStartDate() + "=>" + assemblySheet.getEleStartDate()
                + "<br>结束时间：" + oldAsseSheet.getEleEndDate() + "=>" + assemblySheet.getEleEndDate()
                + "<br>反馈内容：" + oldAsseSheet.getEleBackRemark() + "=>" + assemblySheet.getEleBackRemark());
        return 1;
    }


    public int selectDispatchCount() {
        return  dispatchMapper.selectDispatchCount();
    }
}
